package com.example.yangxu0703.thundermapclient.bluetooth;

import android.bluetooth.BluetoothSocket;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import static com.example.yangxu0703.thundermapclient.bluetooth.AbsBluetooth.FileNotFind;

/*
    不管蓝牙的连接状态，在connectThread中进行判断操作确定socket一定是连接的
* */
public class SendMsg extends Thread {
    private BluetoothSocket socket;
    private File file;
    private String msg;
    private OutputStream os;
    private int mode = 0;
    private FileInputStream fis;
    private AbsBluetooth.Listerner listerner;
    private int lenth = 0;

    public SendMsg(BluetoothSocket socket) {
        this.socket = socket;
    }

    public void setFileSend(File fileSend) {
        this.file = fileSend;
        mode = 1;
    }

    public void setMsg(String msg) {
        this.msg = msg;
        mode = 0;
    }

    @Override
    public void run() {
        try {
            os = socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        Log.i("MSG",msg+"--------------"+file.getAbsoluteFile());
        switch (mode) {
            case 0:
                try {
                    os.write(msg.getBytes("UTF-8"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    os.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //不断开socket
                break;
            case 1:
                try {
                    os.write(file.getName().getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                byte[] buffer = new byte[1024];
                try {
                    fis = new FileInputStream(file);
                    if (fis != null) {
                        listerner.observerConnection(FileNotFind);
                    }
                    while ((lenth = fis.read(buffer)) != -1) {
                        os.write(buffer);
                    }
                    fis.close();
                    fis = null;
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                break;
        }


    }

    public void setListerner(AbsBluetooth.Listerner listerner) {
        this.listerner = listerner;
    }

}
